package com.intelligent.mts.da.handler;

import com.intelligent.mts.core.utils.AppConst;
import com.intelligent.mts.da.utils.MessageUtils;
import com.intelligent.mts.da.xmlmessage.HttpXmlResponse;
import com.intelligent.mts.da.message.ReceiveMessage;
import com.intelligent.mts.da.xmlmessage.Validate;
import com.intelligent.mts.da.xmlmessage.validateReturnMsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Administrator on 2016/9/5.
 */

public class HttpOutHandler extends ChannelInboundHandlerAdapter {
    public static Logger logger = LoggerFactory.getLogger(ValidateHandler.class);
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("Start HttpOut process.");

        if (msg instanceof Validate){
            ctx.writeAndFlush(new HttpXmlResponse(null, msg));
            return;
        }

        validateReturnMsg validateReturnMsg = new validateReturnMsg();
        String result1 = msg.toString();
        ReceiveMessage receiveMessage = MessageUtils.encodeHttpMessages(result1);
        String startFlag = receiveMessage.getStartFlag();
        String stationId = receiveMessage.getStationId();
        String outName = "";
        String outValue ="";
        if (stationId.equals(AppConst.STATION_0750))
        {
            outName = AppConst.FINISH_GOOD_KEY_FCT;
            outValue = receiveMessage.getFct();
        }else if (stationId.equals(AppConst.STATION_1050)){
            outName = AppConst.FINISH_GOOD_KEY_EOL;
            outValue = receiveMessage.getEol();
        }
        switch (startFlag){
            case AppConst.START_VALIDATE_RESP:
                validateReturnMsg.setService("GetProgNameByBatch");
//                validateReturnMsg.setInfo(outName + " for CA " + outValue);
                validateReturnMsg.setInfo(outValue);
                break;
            case AppConst.START_STATUS_RESP :
                validateReturnMsg.setService("SendTestResult");
                break;
        }
        validateReturnMsg.setResult(receiveMessage.getResult());
        ctx.writeAndFlush(new HttpXmlResponse(null, validateReturnMsg));

    }
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            logger.warn("Unexpected exception from com.intelligent.mts.da.handler " + cause);
            ctx.fireExceptionCaught(cause);
        }


}


